//
//  PlaceField.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/1.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay



open class GlobalPlaceField:FieldView{
    public let valueL = UILabel()
    open override func addLayoutRules() {
        
        let bt = UIButton()
        
        self.eelay = [
            [valueL,[ee.T.L.B.R]],
            [bt,[ee.T.L.B.R]],
        ]
        
        _ = valueL.ui.cl_666.font14
        self.isUserInteractionEnabled = true
        bt.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
    }
    
    open override func get_string_value() -> String {
        return mo.model["value",""].escapeHeadTailSpace()
    }
    
    public let picker = AddressSelector()

    public func parserValues() -> (String?,String?,String?) {
        var province_id:String? = nil
        var city_id:String? = nil
        var area_id:String? = nil
        
        if let dict = mo.model[FK.value,""].JsonDictionary{
            let province = dict["province.\(PlaceNode.province.valueKey)",""]
            let city = dict["city.\(PlaceNode.city.valueKey)",""]
            let area = dict["area.\(PlaceNode.area.valueKey)",""]
            if province.len > 0
            {
                province_id = province
            }
            if city.len > 0
            {
                city_id = city
            }
            if area.len > 0
            {
                area_id = area
            }
        }
        return (province_id,city_id,area_id)
        
    }
    
    
    @objc open func selectAction()
    {
        if mo.model[FK.editble,"YES"] == "NO"
        {
            return
        }
        var addresses = [String]()
        let v = parserValues()
        if let province = v.0{
            addresses.append("中国")
            addresses.append(v.0 ?? "")
            addresses.append(v.1 ?? "")
            addresses.append(v.2 ?? "")
        }
        else{
            if let objs = mo.model[FK.value,"[]"].JsonArray{
                for address in Each<NSMutableDictionary>(objs) {
                    addresses.append(address["name",""])
                }
            }
        }
        
        

        if let ctr = self.controller
        {
            
            ctr.present(picker, animated: false) {
                
            }
            picker.address = addresses
//            picker.show(at: ctr)
        }
        weak var wself = self
        
        picker.confirm = {
            item,list in
            let v =  list.rawJson ?? "[]"
            wself?.mo.model[FK.value] = v
            print("+++_---00---|\(v)")
            wself?.save(v)
            wself?.mo_model_reload()
        }
//        picker.selectAction = {
//            values,dict,name in
//            let str = "\(values.province ?? "**")|\(values.city ?? "**")|\(values.area ?? "**")"
//            wself?.mo.model["_value"] = str
////            wself?.mo.model["value"] = dict.rawJson ?? "{}"
////            wself?.mo.model["NameValue"] = name
//            wself?.save(dict.rawJson ?? "{}")
//            wself?.mo_model_reload()
//            //            print("-----|\(values)--\(list)")
//        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: FK.SaveJoFormNotify), object: nil)
    }
    
    
    public static func displayStr(address:NSMutableDictionary)->String{
        let desc = address["description",""]
        if let list = desc.JsonArray{
           var strs:[String] = []
           for address in Each<NSMutableDictionary>(list) {
               strs.append(address["name",""])
           }
            strs.append(address["address",""])
           let newlist = strs.filterDuplicate()
           return newlist.joined(separator: ",")
        
        }else{
            let list = [address["province",""],address["city",""],address["area",""],address["address",""]]
            let newlist = list.filterDuplicate()
            return newlist.joined(separator: ",")

        }
        
    }
    
    open var addressDisplay:String{
        get{
//            print("____))))--",mo.model[FK.value])
            if let dict = mo.model[FK.value,""].JsonDictionary{
//                print("_____OO-S",dict)
                let list = [dict["province.\(_keys.province.name)",""],dict["city.\(_keys.city.name)",""],dict["area.\(_keys.area.name)",""]]
                
                let newlist = list.filterDuplicate()
                
                return newlist.joined(separator: ",")
            }
            
            if let list = mo.model[FK.value,""].JsonArray{
                           
                var strs:[String] = []
                for address in Each<NSMutableDictionary>(list) {
                    strs.append(address["name",""])
                }
                let newlist = strs.filterDuplicate()
                return newlist.joined(separator: ",")
            }
                       
            
            return ""
        }
    }
    
    open override func mo_model_reload() {
        //以中文值作为value
        let valueName = self.addressDisplay
        if valueName.len > 0
        {
            self.valueL.text = valueName
            valueL.ui.font(font: FieldView.valueStyle.font).text(color: FieldView.valueStyle.color)
        }
        else
        {
            valueL.ui.font(font: FieldView.holderStyle.font).text(color: FieldView.holderStyle.color).text(mo.model[FK.placeholder,""])
        }
    }
    
}


open class PlaceField:FieldView{
    public let valueL = UILabel()
    open override func addLayoutRules() {
        
        let bt = UIButton()
        
        self.eelay = [
            [valueL,[ee.T.L.B.R]],
            [bt,[ee.T.L.B.R]],
        ]
        
        _ = valueL.ui.cl_666.font14
        self.isUserInteractionEnabled = true
        bt.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
    }
    
    open override func get_string_value() -> String {
        return mo.model["value",""].escapeHeadTailSpace()
    }
    
    public let picker = AddressPiker()

    public func parserValues() -> (String?,String?,String?) {
//        let cn_address = mo.model["NameValue","云南省 昆明市 五华区"]
//        let idValues = Place.addressIDs(with: cn_address)
//        let strs = idValues.components(separatedBy: "|")
//
//
//        if strs.count > 2
//        {
//            var l1:String? = strs[0]
//            var l2:String? = strs[1]
//            var l3:String? = strs[2]
//
//            if l1 == "**" {
//                l1 = nil
//            }
//            if l2 == "**" {
//                l2 = nil
//            }
//            if l3 == "**" {
//                l3 = nil
//            }
//            return (l1,l2,l3)
//        }
        var province_id:String? = nil
        var city_id:String? = nil
        var area_id:String? = nil

        if let dict = mo.model[FK.value,""].JsonDictionary{
            let province = dict["province.\(PlaceNode.province.valueKey)",""]
            let city = dict["city.\(PlaceNode.city.valueKey)",""]
            let area = dict["area.\(PlaceNode.area.valueKey)",""]
            if province.len > 0
            {
                province_id = province
            }
            if city.len > 0
            {
                city_id = city
            }
            if area.len > 0
            {
                area_id = area
            }
        }
        return (province_id,city_id,area_id)
        
        
    }
    
    
    @objc open func selectAction()
    {
        if mo.model[FK.editble,"YES"] == "NO"
        {
            return
        }
        let vls = parserValues()
        picker.commingValues = vls
//        picker.values = vls
        if let ctr = self.controller
        {
            picker.show(at: ctr)
        }
        weak var wself = self
        picker.selectAction = {
            values,dict,name in
            let str = "\(values.province ?? "**")|\(values.city ?? "**")|\(values.area ?? "**")"
            wself?.mo.model["_value"] = str
//            wself?.mo.model["value"] = dict.rawJson ?? "{}"
//            wself?.mo.model["NameValue"] = name
            wself?.save(dict.rawJson ?? "{}")
            wself?.mo_model_reload()
            //            print("-----|\(values)--\(list)")
        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: FK.SaveJoFormNotify), object: nil)
    }
    
    
    open var addressDisplay:String{
        get{
            if let dict = mo.model[FK.value,""].JsonDictionary{
                
                let list = [dict["province.\(_keys.province.name)",""],dict["city.\(_keys.city.name)",""],dict["area.\(_keys.area.name)",""]]
                
                let newlist = list.filterDuplicate()
                
                return newlist.joined(separator: " ")
            }
            return ""
        }
    }
    
    open override func mo_model_reload() {
        //以中文值作为value
        let valueName = self.addressDisplay
        if valueName.len > 0
        {
            self.valueL.text = valueName
            valueL.ui.font(font: FieldView.valueStyle.font).text(color: FieldView.valueStyle.color)
        }
        else
        {
            valueL.ui.font(font: FieldView.holderStyle.font).text(color: FieldView.holderStyle.color).text(mo.model[FK.placeholder,""])
        }
    }
    
}
